#include "widget.h"
#include "ui_widget.h"
#include <QTreeWidgetItem>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置TreeWidget的根节点名称
    ui->treeWidget->setHeaderLabel("动物");

    //新增顶层元素
    QTreeWidgetItem *item1 = new QTreeWidgetItem();
    item1->setText(0,"猫");
    //每个item有多个列
    item1->setText(1,"猫猫");

    //新增顶层元素
    QTreeWidgetItem *item2 = new QTreeWidgetItem();
    item2->setText(0,"狗");

    //新增顶层元素
    QTreeWidgetItem *item3 = new QTreeWidgetItem();
    item3->setText(0,"鸟");

    //添加顶层元素
    ui->treeWidget->addTopLevelItem(item1);
    ui->treeWidget->addTopLevelItem(item2);
    ui->treeWidget->addTopLevelItem(item3);

    //添加子元素
    QTreeWidgetItem *item11 = new QTreeWidgetItem();
    item11->setText(0,"狸猫");

    QTreeWidgetItem *item12 = new QTreeWidgetItem();
    item12->setText(0,"英短");

    QTreeWidgetItem *item12_1 = new QTreeWidgetItem();
    item12_1->setText(0,"蓝色的英短");

    item12->addChild(item12_1);

    item1->addChild(item11);
    item1->addChild(item12);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addTopLevelItem_clicked()
{
    //构建一个QTreeWidget对象，更具lineEdit的文本
    QTreeWidgetItem *item = new QTreeWidgetItem();
    item->setText(0,ui->lineEdit->text());

    //添加顶层节点
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_addItem_clicked()
{
    //获取当前选中的元素
    QTreeWidgetItem * curItem = ui->treeWidget->currentItem();
    if(curItem == nullptr){
        //没有选中元素,直接返回
        return;
    }
    //构建一个QTreeWIdget对象,更具linedit的文本
    QTreeWidgetItem *item = new QTreeWidgetItem();
    item->setText(0,ui->lineEdit->text());
    //添加子元素
    curItem->addChild(item);
}

void Widget::on_pushButton_deleteItem_clicked()
{
    //获取当前选中的元素
    QTreeWidgetItem *curItem = ui->treeWidget->currentItem();
    if(curItem == nullptr){
        return;
    }

    //删除选中元素，需要先找到选中元素的父元素，有两种情况
    QTreeWidgetItem *parent = curItem->parent();
    if(parent == nullptr){
        //说明当前选中的元素是顶层节点
        int index = ui->treeWidget->indexOfTopLevelItem(curItem);
        ui->treeWidget->takeTopLevelItem(index);
    }else{
        //是子节点
        parent->removeChild(curItem);
    }
}
